<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-08
 * Time: 15:16
 */

namespace app\common\service;


use think\facade\Config;

class WxOcTemplateMessage
{
    private $sendUrl = ""; //发送消息模板的URL

    protected $template_id; //所需下发的模板消息的id
    protected $data;        //模板内容，不填则下发空模板

    public function __construct()
    {
        $accessToken = (new WxAccessToken('wx_oc1_access_token',get_wx_config('oc_app_id'), get_wx_config('oc_app_secret')))->get();

        $this->sendUrl = sprintf(Config::get('wx.oc_send_template_message_url'),
            $accessToken);
    }

    /**
     * 发送模版消息给指定的用户
     * @param $openid 用户的openid
     * @param string $url 点击模版卡片后跳转的url地址
     * @param array $miniprogram 点击模版卡片后跳转的小程序页面
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function sendTemplateMessage($openid, $url = '', $miniprogram = [])
    {
//        {
//            "touser":"OPENID",
//           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
//           "url":"http://weixin.qq.com/download",
//           "miniprogram":{
//            "appid":"xiaochengxuappid12345",
//             "pagepath":"index?foo=bar"
//           },
//           "data":{
//            "first": {
//                "value":"恭喜你购买成功！",
//                       "color":"#173177"
//                   },
//                   "keyword1":{
//                "value":"巧克力",
//                       "color":"#173177"
//                   },
//                   "keyword2": {
//                "value":"39.8元",
//                       "color":"#173177"
//                   },
//                   "keyword3": {
//                "value":"2014年9月22日",
//                       "color":"#173177"
//                   },
//                   "remark":{
//                "value":"欢迎再次购买！",
//                       "color":"#173177"
//                   }
//           }
//       }
        if (empty($miniprogram)) {
            $data = [
                'touser'=>$openid,
                'template_id'=>$this->template_id,
                'url'=>$url,
                'data'=>$this->data
            ];
        } else {
            $data = [
                'touser'=>$openid,
                'template_id'=>$this->template_id,
                'miniprogram'=>$miniprogram,
                'data'=>$this->data
            ];
        }

        $result = curl_post($this->sendUrl,$data);

        if (!$result) {
            throw new \Exception('请求数据发送错误，url:'. $this->sendUrl);
        }

        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            throw new \Exception('公众号发送模版消息失败，code：'.$result['errcode'].',msg：'.$result['errmsg']);
        }
    }
}